package com.youmingxing.adpter.RecyclerViewAdapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.youmingxing.R;

import org.json.JSONArray;
import org.json.JSONObject;

import jp.wasabeef.glide.transformations.CropCircleTransformation;

/**
 * @author evilyin(ChenZhixi)
 * @since 16/1/21
 */
public class VoteRecyclerViewAdapter extends RecyclerView.Adapter<VoteRecyclerViewAdapter.ViewHolder>{

    private Context context;
    private JSONArray dataList;

    public VoteRecyclerViewAdapter(Context context, JSONArray dataList) {
        this.context = context;
        this.dataList = dataList;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public ViewHolder(View arg0) {
            super(arg0);
        }

        TextView voteNumber;
        ImageView image;

    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = View.inflate(context, R.layout.item_voter, null);
        ViewHolder holder = new ViewHolder(view);
        holder.voteNumber = (TextView) view.findViewById(R.id.vote_number);
        holder.image = (ImageView) view.findViewById(R.id.voter_image);

        return holder;
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        JSONObject thisVoter = dataList.optJSONObject(position);
        holder.voteNumber.setText(thisVoter.optInt("votenum") + "票");
        Glide.with(context).load(thisVoter.optString("headimg"))
                .placeholder(R.drawable.default_avatar).error(R.drawable.default_avatar)
                .bitmapTransform(new CropCircleTransformation(
                        context)).crossFade().into(holder.image);

        if (mOnItemClickListener != null)
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mOnItemClickListener.onItemClick(holder.itemView, position);
                }
            });
    }

    @Override
    public int getItemCount() {
        return dataList.length();
    }


    public interface OnItemClickListener {
        void onItemClick(View view, int position);
    }

    private OnItemClickListener mOnItemClickListener;

    public void setOnItemClickListener(OnItemClickListener mOnItemClickListener) {
        this.mOnItemClickListener = mOnItemClickListener;
    }
}
